#include "Button.h"

Button::Button(std::string buttonName, int posX, int posY,
		Widget *parent, Listener* listener,SDL_Surface* presssedStatus,SDL_Surface* defaultStatus) :
	Widget(posX, posY, parent) {


	this->buttonName = buttonName;
	this->pressedSurface = presssedStatus;
	this->defaultSurface = defaultStatus;

	this->parcel = getPosition();
	parcel.height = this->pressedSurface->h;// Es indistinto cualquiera de las
	parcel.width = this->pressedSurface->w;// dos superficies por que son iguales

	this->activeSurface = this->defaultSurface;// El boton activo es el no presionado

	this->listener = listener;

	SDL_Color textColor = { 255, 255, 255 };
	TTF_Font *font = NULL;
	font = TTF_OpenFont("./res/font/Neuton.ttf", 18);

	if (font == NULL) {
		Logger::log("Button", "createButtonSurfaces", "No se cargó la fuente");
	}

	if (this->buttonName != "") {
		char* c_buttonName = new char[this->buttonName.size() + 1];
		strcpy(c_buttonName, this->buttonName.c_str());
		SDL_Surface* textSurface = TTF_RenderText_Solid(font, c_buttonName,
				textColor);
		delete[] c_buttonName;

		SDL_Rect rect;

		rect.x = (this->parcel.width - textSurface->w) / 2;
		rect.y = (this->parcel.height - textSurface->h) / 2;
		rect.w = textSurface->w;
		rect.h = textSurface->h;

		SDL_BlitSurface(textSurface, NULL, this->defaultSurface, &rect);
		SDL_BlitSurface(textSurface, NULL, this->pressedSurface, &rect);
		SDL_FreeSurface(textSurface);
	}
	TTF_CloseFont(font);

	state = 0;
	pressed = false;
	mouseIsOver = false;

}

Button::~Button() {
	SDL_FreeSurface(pressedSurface);
	SDL_FreeSurface(defaultSurface);
}

void Button::handleEvent(Event event) {
	mouseIsOver = mouseOver(event);
	state = event.getType();
}
void Button::resolve() {
	if (state == MouseButtonPressed && mouseIsOver){
		activeSurface = pressedSurface;
		pressed = true;
	}
	if (state == MouseButtonReleased && mouseIsOver && pressed){
		pressed = false;
		activeSurface = defaultSurface;
		listener->execute();
	}
	if (!mouseIsOver){
		activeSurface = defaultSurface;
	}
}

void Button::showOn(SDL_Surface *surface) {
	SDL_Rect rect;
	rect.x = parcel.posX;
	rect.y = parcel.posY;
	rect.w = parcel.width;
	rect.h = parcel.height;
	SDL_BlitSurface(this->activeSurface, NULL, surface, &rect);
}

bool Button::mouseOver(Event event) const {
	return ((event.getXCoordinate() > this->parcel.posX)
			&& (event.getXCoordinate() < this->parcel.posX + this->parcel.width)
			&& (event.getYCoordinate() > this->parcel.posY)
			&& (event.getYCoordinate() < this->parcel.posY
					+ this->parcel.height));
}
